package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"order-master/cache"
	"order-master/models"
	"strconv"
	"time"
)

func OrderAdd(c *gin.Context) {
	order_no, _ := strconv.Atoi(c.PostForm("order_no"))
	pid, _ := strconv.Atoi(c.PostForm("pid"))

	data := models.Order{
		OrderNo: order_no,
		Pid:     pid,
	}
	models.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
	})
	return
}
func OrderList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	offset := (page - 1) * size
	var orderList []models.OrderList

	/*
		SELECT
		  orders.id as OrderId,
		  orders.order_no as OrderNo,
		  orders.pid as Pid,
		  people.per_code as PerCode,
		  people.per_name as PerName,
		  people.per_num as PerNum
		FROM
		  orders
		  LEFT JOIN people ON people.id = orders.pid
	*/
	redis_key := "data_list_page_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Table("orders").
			Joins("LEFT JOIN people ON people.id = orders.pid").
			Select(
				"orders.id as OrderId",
				"orders.order_no as OrderNo",
				"orders.pid as Pid",
				"people.per_code as PerCode",
				"people.per_name as PerName",
				"people.per_num as PerNum").
			Offset(offset).Limit(size).Debug().Find(&orderList)
		jsonData, _ := json.Marshal(orderList)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &orderList)
	}
	var total int64
	models.DB.Model(&models.Order{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"data":  orderList,
		"total": total,
		"msg":   "ok",
	})
	return
}
